﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;

namespace Fks.Win.Attriber
{
    public partial class frm_Main : Form
    {
        private int Acount = 0;
        private int Ycount = 0;

        private Thread thread;  //需要处理线程
        private bool thread_state = false;  //处理状态 
        StringBuilder sb_error = new StringBuilder();  //线程操作日志

        public frm_Main()
        {
            InitializeComponent();
        }

        private void btn_SelectPath_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.txt_Exts.Text))
            {
                MessageBox.Show("请设置扩展名！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else
            {
                DialogResult dr = this.folderBrowserDialog1.ShowDialog();
                this.folderBrowserDialog1.Description = "设置你的工作目录";
                this.folderBrowserDialog1.ShowNewFolderButton = false;

                if (dr == System.Windows.Forms.DialogResult.OK)
                { 
                    //获得文件列表
                    this.tex_Path.Text = this.folderBrowserDialog1.SelectedPath;
                    Refresh_List();
                }
            }
        }

        private void btn_Set_Click(object sender, EventArgs e)
        {
            if (thread_state)
            {
                MessageBox.Show("线程正在处理中！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            if (this.che_List.Items.Count < 1)
            {
                MessageBox.Show("请选择你要处理的文件列表！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.btn_SelectPath.Focus();
                return;
            }

            if (this.tex_FileName.Text.Length < 1)
            {
                MessageBox.Show("请设置重命名的文件规则！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.tex_FileName.Focus();
                return;
            }

            //将扩展名存储起来
            Fks.Common.Win.FrameworkUntity.AuConfig_AppSettings("exts", this.txt_Exts.Text);
            Fks.Common.Win.FrameworkUntity.AuConfig_AppSettings("new_filename", this.tex_FileName.Text);

            string error = string.Empty;

            var Litem = getCheList();  //获得需要处理的记录

            this.progressBar1.Visible = true;
            this.btn_Set.Enabled = false;

            this.progressBar1.Maximum = Litem.Count;
            this.progressBar1.Minimum = 0;
            this.progressBar1.Value = 0;

            #region 线程

            //线程调用
            //thread = new Thread(ReName);
            //thread.Start();

            ReName();

            #endregion

            this.progressBar1.Visible = false;
            this.btn_Set.Enabled = true;

            //初始化显示
            Refresh_List();

            #region 日志记录

            if (!string.IsNullOrEmpty(sb_error.ToString()))
                Fks.Log.sLog.Default.Set(Fks.Log.sLog.LogType.WinUI, GetType().FullName, sb_error.ToString());

            #endregion

            MessageBox.Show("需要处理的文件：" + Acount + "个，成功处理：" + Ycount + "个！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        /// <summary>
        /// 将当前列表转换集合方式
        /// </summary>
        /// <returns></returns>
        List<Fks.Common.Win.EntityUntity.ListItem> getCheList()
        {
            List<Fks.Common.Win.EntityUntity.ListItem> li = new List<Common.Win.EntityUntity.ListItem>();

            for (int i = 0; i < this.che_List.Items.Count; i++)
            {
                if (this.che_List.GetItemChecked(i))
                    li.Add((Fks.Common.Win.EntityUntity.ListItem)this.che_List.Items[i]);
            }

            return li;
        }

        /// <summary>
        /// 重命名的具体方法
        /// </summary>
        void ReName()
        {
            thread_state = true;

            Acount = 0;
            Ycount = 0;

            string error = string.Empty;
            string TmpFileName = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_FileName, "Text"));

            string TmpTitleFix = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_Title, "Text"));
            string TmpAuthor = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_Author, "Text"));
            string TmpAlbumTitle = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_AlbumTitle, "Text"));
            string TmpYear = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_Year, "Text"));
            string TmpComment = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_Comment, "Text"));

            string TmpFind = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_Find, "Text"));
            string TmpReplace = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_Replace, "Text"));

            var Litem = getCheList();
            for (int i = 0; i < Litem.Count; i++)
            {
                Acount++;

                string TmpOFileName_key = Fks.Common.TextIoUntity.Comm.getFile(Convert.ToString(Litem[i].Value));  //旧文件的名称
                string TmpOFileName_value = Convert.ToString(Litem[i].Value);  //旧文件名绝对全地址
                string TmpFolder = Fks.Common.TextIoUntity.Comm.getDirectory(TmpOFileName_value);  //资源目录

                string TmpIndex = fix_Index(i + 1, 3);
                string TmpNFileName = format_Regefix(TmpFileName, TmpIndex, TmpOFileName_key, TmpFolder, false);  //新文件名
                if (!string.IsNullOrEmpty(TmpFind))
                    TmpNFileName = TmpNFileName.Replace(TmpFind, TmpReplace);

                //1.先重新命名
                int m = Ycount + 1;
                this.tss_labe_return.Text = ",正在处理第" + m + "个！";
                if (Fks.Common.TextIoUntity.Comm.RenameFile(TmpOFileName_value, TmpFolder + TmpNFileName, out error))
                {
                    if (this.che_SetID3.Checked)
                    {
                        #region 2.设置其ID3属性

                        try
                        {
                            string TmpTitle = format_Regefix(TmpTitleFix, TmpIndex, TmpNFileName, TmpFolder, true);

                            Fks.Common.Win.Lib.MediaUntity mu = new Fks.Common.Win.Lib.MediaUntity(Environment.CurrentDirectory);

                            mu.Title = TmpTitle;
                            mu.Author = TmpAuthor;
                            mu.AlbumTitle = TmpAlbumTitle;
                            mu.Year = Convert.ToUInt32(TmpYear);
                            mu.Comment = TmpComment;

                            mu.Commit(TmpFolder + TmpNFileName);
                        }
                        catch
                        {
                        }

                        #endregion
                    }

                    Ycount++;
                    this.tss_labe_return.Text = "已处理：" + Ycount.ToString() + "个";
                    progressBar1.Value = Ycount;

                    //线程方法
                    //this.Invoke((EventHandler)delegate
                    //{
                    //    progressBar1.PerformStep();
                    //});

                    if (!string.IsNullOrEmpty(error))
                        sb_error.AppendLine("资源：" + TmpOFileName_key + " 重命名发生错误：" + error);
                }
            }

            thread_state = false;
        }

        /// <summary>
        /// 格式正规则表达试的内容
        /// </summary>
        /// <param name="Cvalue">需要格式化处理的值</param>
        /// <param name="TmpIndex">数字序列</param>
        /// <param name="TmpOFileName">原文件名</param>
        /// <param name="TmpFolder">目录名</param>
        /// <param name="FixEx">是否去除扩展名</param>
        string format_Regefix(string Cvalue, string TmpIndex, string TmpOFileName, string TmpFolder, bool FixEx)
        {
            string result = string.Empty;

            if (!string.IsNullOrEmpty(Cvalue))
            {
                //处理替换
                if (!string.IsNullOrEmpty(this.tex_Find.Text))
                    TmpOFileName = TmpOFileName.Replace(this.tex_Find.Text, this.tex_Replace.Text);

                //处理公式
                result = Cvalue.Replace("[C]", TmpIndex);   //序号
                result = result.Replace("[N]", TmpOFileName);   //文件名

                //目录的处理
                string[] TmpFolder_Length = TmpFolder.Split('\\');
                result = result.Replace("[D]", TmpFolder_Length[TmpFolder_Length.Length - 2]);

                if (!FixEx)
                    result = result.Replace("[E]", Fks.Common.TextIoUntity.Comm.getExt(TmpOFileName));
                else
                    result = result.Replace("." + Fks.Common.TextIoUntity.Comm.getExt(TmpOFileName), "");
            }

            return result;
        }

        /// <summary>
        /// 给序列号补足位数显示
        /// </summary>
        /// <param name="i">需要补足的数字</param>
        /// <param name="Length">补足的位数</param>
        string fix_Index(int i, int Length)
        {
            string result = string.Empty;

            if (i.ToString().Length < Length)
            {
                for (int m = 0; m < Length - i.ToString().Length; m++)
                {
                    result += "0";
                }

                result += i.ToString();
            }
            else
            {
                result = i.ToString();
            }

            return result;
        }

        private void btn_Esc_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void frm_Main_Load(object sender, EventArgs e)
        {
            this.tex_Year.Text = DateTime.Now.ToString("yyyy");
            this.txt_Comment.Text = Application.StartupPath + "\\comment.txt";
            this.txt_CommPath.Text = Application.StartupPath + "\\Atts";

            //初始化日志系统
            Fks.Log.sLog.Default.Init(Fks.Log.sLog.LogApdate.LocalFile, Application.StartupPath);

            //读取扩展名
            this.txt_Exts.Text = Fks.Common.FrameworkUntity.ConfigHelper.GetConfig_AppSettings("exts");
            this.tex_FileName.Text = Fks.Common.FrameworkUntity.ConfigHelper.GetConfig_AppSettings("new_filename");
        }

        private void che_SetID3_CheckedChanged(object sender, EventArgs e)
        {
            if (che_SetID3.Checked)
                this.panel_ID3.Enabled = true;
            else
                this.panel_ID3.Enabled = false;
        }

        private void tex_Path_TextChanged(object sender, EventArgs e)
        {
            Refresh_List();
        }

        private void che_Snext_CheckedChanged(object sender, EventArgs e)
        {
            Refresh_List();
        }

        private void tex_Rfix_TextChanged(object sender, EventArgs e)
        {

        }

        #region 初始化选择的文件及目录

        int m = 0;

        void Refresh_List()
        {
            if (!string.IsNullOrEmpty(this.tex_Path.Text))
            {
                this.che_List.Items.Clear();
                m = 0;

                Refresh_for_RootPath(this.tex_Path.Text);
            }
        }

        /// <summary>
        /// 刷新列表，根据根目录
        /// </summary>
        /// <param name="tex_Path">需要显示的根目录</param>
        void Refresh_for_RootPath(string tex_Path)
        {
            //当前目录处理
            Refresh_for_DF(this.tabControl1.SelectedTab.Tag.ToString(), tex_Path);

            if (this.che_Snext.Checked)
            {
                DirectoryInfo[] GetDires = Fks.Common.Win.TextIoUntity.GetDirectory(tex_Path);
                for (int i = 0; i < GetDires.Length; i++)
                {
                    //子目录处理
                    if (GetDires[i] != null && GetDires[i].FullName != null)
                    {
                        Refresh_for_DF(this.tabControl1.SelectedTab.Tag.ToString(), GetDires[i].FullName);
                    }
                }
            }
        }

        /// <summary>
        /// 根据Tab显示相应的列表
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="tex_Path"></param>
        void Refresh_for_DF(string tab, string tex_Path)
        {
            if (tab == "tab_rename")
                Refresh_for_FileList(tex_Path);
            else if (tab == "tab_zip")
                Refresh_for_DirectoryList(tex_Path);
        }

        /// <summary>
        /// 显示目录列表
        /// </summary>
        /// <param name="tex_Path">需要显示子目录及文件</param>
        void Refresh_for_DirectoryList(string tex_Path)
        {
            DirectoryInfo[] GetDirectory = Fks.Common.Win.TextIoUntity.GetDirectory(tex_Path);

            this.che_List.DisplayMember = "key";
            this.che_List.ValueMember = "value";

            for (int i = 0; i < GetDirectory.Length; i++)
            {
                bool IsTrue = true;

                //是否要过滤...
                int rcount = 0;
                if (!string.IsNullOrEmpty(this.tex_Rfix.Text))
                {
                    string[] rvalue = Fks.Common.StringUntity.Cha.Farray(this.tex_Rfix.Text.Trim(), ",", out rcount);

                    for (int x = 0; x < rcount; x++)
                    {
                        if (GetDirectory[i].Name.ToLower().Contains(rvalue[x]))
                            IsTrue = false;
                    }
                }

                if (IsTrue)
                {
                    this.che_List.Items.Add(new Fks.Common.Win.EntityUntity.ListItem(GetDirectory[i].Name, GetDirectory[i].FullName), true);
                    m++;
                }
            }

            this.che_List.Refresh();
            this.tss_labe_info.Text = "共有目录：" + m.ToString() + "个";
        }

        /// <summary>
        /// 显示文件列表
        /// </summary>
        /// <param name="Path">需要显示子目录及文件</param>
        void Refresh_for_FileList(string Path)
        {
            FileInfo[] GetFiles = Fks.Common.Win.TextIoUntity.GetFiles(Path);

            this.che_List.DisplayMember = "key";
            this.che_List.ValueMember = "value";

            for (int i = 0; i < GetFiles.Length; i++)
            {
                //if (GetFiles[i].Name.ToLower().Contains(".mp3") || GetFiles[i].Name.ToLower().Contains(".wma"))
                if (Fix_FileName(GetFiles[i].Name))
                {
                    bool IsTrue = true;

                    //是否要过滤...
                    int rcount = 0;
                    if (!string.IsNullOrEmpty(this.tex_Rfix.Text))
                    {
                        string[] rvalue = Fks.Common.StringUntity.Cha.Farray(this.tex_Rfix.Text.Trim(), ",", out rcount);

                        for (int x = 0; x < rcount; x++)
                        {
                            if (GetFiles[i].Name.ToLower().Contains(rvalue[x]))
                                IsTrue = false;
                        }
                    }

                    if (IsTrue)
                    {
                        this.che_List.Items.Add(new Fks.Common.Win.EntityUntity.ListItem(GetFiles[i].FullName, GetFiles[i].FullName), true);
                        m++;
                    }
                }
            }

            this.che_List.Refresh();
            this.tss_labe_info.Text = "共有文件：" + m.ToString() + "个";
        }

        /// <summary>
        /// 检验文件是否是需要处理的文件类型
        /// </summary>
        /// <param name="fileName">需要处理文件</param>
        /// <returns></returns>
        bool Fix_FileName(string fileName)
        {
            string[] exts = this.txt_Exts.Text.ToLower().Split('|');
            if (exts.Length > 0)
            {
                for (int i = 0; i < exts.Length; i++)
                {
                    if (fileName.Contains(exts[i]))
                        return true;
                }
            }

            return false;
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedTab.Tag.ToString() == "tab_zip")
                this.tex_Rfix.Text = "#";

            Refresh_List();
        }

        #endregion

        private void btn_esc_forzip_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btn_zip_Click(object sender, EventArgs e)
        {
            if (thread_state)
            {
                MessageBox.Show("线程正在处理中！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            this.progressBar1.Visible = true;
            this.btn_zip.Enabled = false;

            var Litem = getCheList();  //获得需要处理的记录

            this.progressBar1.Maximum = Litem.Count;
            this.progressBar1.Minimum = 0;
            this.progressBar1.Value = 0;

            //线程启用
            //thread = new Thread(Zip_File);
            //thread.Start();

            Zip_File();

            this.progressBar1.Visible = false;
            this.btn_zip.Enabled = true;

            //初始化显示
            Refresh_List();

            #region 日志记录

            if (!string.IsNullOrEmpty(sb_error.ToString()))
                Fks.Log.sLog.Default.Set(Fks.Log.sLog.LogType.WinUI, GetType().FullName, sb_error.ToString());

            #endregion

            MessageBox.Show("需要生城压缩的文件夹" + Acount.ToString() + "个，实际生成" + Ycount.ToString() + "个！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        void Zip_File()
        {
            thread_state = true;

            StringBuilder sb_out = new StringBuilder();
            string error = string.Empty;

            string TmpZipFind = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_zip_find, "Text"));
            string TmpZipFind_New = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_zip_find_new, "Text"));
            string TmpPath = Convert.ToString(Fks.Common.Win.InvokerUntity.Get(this.tex_Path, "Text"));

            var Litem = getCheList();

            this.che_List.DisplayMember = "key";
            this.che_List.ValueMember = "value";

            for (int i = 0; i < Litem.Count; i++)
            {
                Acount++;

                string TmpODir_key = ((Fks.Common.Win.EntityUntity.ListItem)Litem[i]).Key;  //文件名
                string TmpODir_value = Convert.ToString(((Fks.Common.Win.EntityUntity.ListItem)Litem[i]).Value);  //文件全地址

                string TmpNDir = TmpODir_key;
                if (!string.IsNullOrEmpty(TmpZipFind))
                    TmpNDir = TmpODir_key.Replace(TmpZipFind, TmpZipFind_New);

                int m = Ycount + 1;
                this.tss_labe_return.Text = ",正在处理第" + m.ToString() + "个！";
                if (Create_Zip(TmpODir_value, TmpPath + "\\", TmpNDir, out error))
                {
                    sb_out.AppendLine(TmpNDir);
                    Fks.Common.Win.InvokerUntity.Set(this.rTex_zip_out, "Text", sb_out.ToString());

                    Ycount++;
                    this.tss_labe_return.Text = "已处理：" + Ycount.ToString() + "个";
                    progressBar1.Value = Ycount;

                    //线程方法
                    //this.Invoke((EventHandler)delegate
                    //{
                    //    progressBar1.PerformStep();
                    //});

                    if (!string.IsNullOrEmpty(error))
                        sb_error.AppendLine("资源：" + TmpODir_key + " 重命名发生错误：" + error);
                }
            }

            thread_state = false;
        }

        /// <summary>
        /// 创建压缩文件
        /// </summary>
        /// <param name="Path">需要压缩目录下的文件，如：D:\123\</param>
        /// <param name="DirPath">压缩的文件存储的位置，如：D:\124\ （不要与Path相同）</param>
        /// <param name="ZipName">压缩的文件名</param>
        /// <param name="error">输出错误信息</param>
        bool Create_Zip(string Path, string DirPath, string ZipName, out string error)
        {
            bool Result = false;
            error = string.Empty;
            try
            {
                string Desc = string.Empty;

                if (Fks.Common.TextIoUntity.Comm.IsFile(this.txt_Comment.Text))
                    Desc = Fks.Common.TextIoUntity.ReadTxt(this.txt_Comment.Text, "gb2312");

                //压缩文件
                string[] files = Fks.Common.TextIoUntity.Comm.getFiles(Path);
                string[] ads_files = Fks.Common.TextIoUntity.Comm.getFiles(this.txt_CommPath.Text);
                string[] atts = new string[files.Length + ads_files.Length];

                //合并文件 
                files.CopyTo(atts, 0);
                ads_files.CopyTo(atts, files.Length);

                //生在压缩文件
                Result = Fks.Common.Lib.ZIPUntity.Zip(atts, DirPath, ZipName, 9, Desc);

                //改名目录 
                if (!Fks.Common.TextIoUntity.Comm.RenameDirectory(Path, Path + "#", out error))
                    Fks.Log.sLog.Default.Set(Fks.Log.sLog.LogType.WinUI, GetType().FullName, "修改：" + Path + "失败！");
            }
            catch (System.Exception ex)
            {
                error = ex.Message;
            }
            return Result;
        }

        private void tex_Rfix_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
                Refresh_List();
        }

        private void Comment_Click(object sender, EventArgs e)
        {
            DialogResult fd = this.openFileDialog1.ShowDialog();
            this.openFileDialog1.Filter = "文本注释|*.txt";
            this.openFileDialog1.Title = "选择注释文件";

            if (fd == System.Windows.Forms.DialogResult.OK)
            {
                this.txt_Comment.Text = this.openFileDialog1.FileName;
            }
        }

        private void btn_Comm_Click(object sender, EventArgs e)
        {
            DialogResult dr = this.folderBrowserDialog2.ShowDialog();
            this.folderBrowserDialog2.Description = "设置你的公共文件目录";
            this.folderBrowserDialog2.ShowNewFolderButton = false;

            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                this.txt_CommPath.Text = this.folderBrowserDialog2.SelectedPath;
            }
        }

    }
}
